package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"

	"gitee.com/anxu/golang-web/src/config"
	"gitee.com/anxu/golang-web/src/routes"
)

func main() {
	port := config.Config.Get("server.address", ":80").(string)
	server := server(port, routes.Router())

	done := make(chan int, 1)
	status := make(chan os.Signal, 1)
	signal.Notify(status, os.Interrupt, os.Kill)

	go shutdown(server, status, done)
	log.Println("Starting HTTP service at", port)
	server.ListenAndServe()

	<-done
}

func server(port string, h http.Handler) *http.Server {
	return &http.Server{
		Addr:    port,
		Handler: h,
	}
}

func shutdown(server *http.Server, status <-chan os.Signal, done chan<- int) {
	<-status
	fmt.Println("\nclosing...")
	if err := server.Shutdown(context.Background()); err != nil {
		fmt.Println(err)
	}
	close(done)
}

// var process int = 0

// func main() {
// 	port := config.Config.Get("server.address", ":80").(string)
// 	server := server(port, routes.Router())

// 	done := make(chan int, 1)
// 	status := make(chan os.Signal, 1)
// 	signal.Notify(status, os.Interrupt, os.Kill)

// 	go shutdown(server, status, done)

// 	log.Println("Starting HTTP service at", port)

// 	server.ListenAndServe()

// 	<-done
// }

// type handler struct {
// 	handler *mux.Router
// }

// func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// 	process++
// 	h.handler.ServeHTTP(w, r)
// 	process--
// }

// func server(port string, h *mux.Router) *http.Server {
// 	return &http.Server{
// 		Addr:    port,
// 		Handler: &handler{h},
// 	}
// }

// func shutdown(server *http.Server, status <-chan os.Signal, done chan<- int) {
// 	<-status

// 	go func() {
// 		if err := server.Shutdown(context.Background()); err != nil {
// 			fmt.Println(err)
// 		}
// 	}()

// 	if process > 0 {
// 		fmt.Printf("\nThere are %d requests being processed\n", process)
// 		fmt.Printf("waiting...\n")
// 	}

// 	for {
// 		// 判断有处理请求，则sleep
// 		if process > 0 {
// 			fmt.Println(process)
// 			time.Sleep(time.Second * 1)
// 			continue
// 		} else {
// 			close(done)
// 			break
// 		}
// 	}
// }
